import { reactive, } from "vue";
import { Api } from "../../../api/api.js";
import router from "../../../router/index.js";
import { GJ_nowTime } from "../../../../static/js/tool.js";
import * as echarts from "echarts";
// import { ElNotification } from 'element-plus';
function expenseListJS() {
  // let {proxy:then} = getCurrentInstance();
  let status = reactive({
    Visible: false,
    userinfo: JSON.parse(window.sessionStorage.getItem("userinfo")),
    initail: [],
    //天数节点
    dayEcharts: null,
    monEcharts: null,
    detailEcharts: null,
    // 横轴数据
    xAxisDay: [],
    // 纵轴数据
    yAxisDay: [],
    // 横轴数据
    xAxisMon: [],
    // 纵轴数据
    yAxisMon: [],
    // 年数据集合
    Expense : "",
    yearDatas : "",
    yearExpense :"",
    monDatas : "",
    monExpense : "",
    dayDatas : "",
    dayExpense : "",
    //请求数据信息
    findData: {
      limit: 12,
      skip: 1,
      pages: "",
      total: "",
      user: ""
    }
  })
  let methodFun = {
    // 获取消费数据
    getExpense:()=> {
      status.findData.user = status.userinfo.user;
      Api.getexpense(status.findData).then((res) => {
        status.initail = res.data[0];
        console.log(status.initail, "getExpense");
        methodFun.init();
      });
    },
    //查看详情
    goDetails:()=> {
      router.push("/expense/details");
    },
        //关闭详情
    closefun:(e)=> {
      let a = e.target.nodeName;
      if (a != "CANVAS") {
        status.Visible = false;
      }
    },
    //初始化
    init:()=> {
      let year = GJ_nowTime("year");
      let mon = `${GJ_nowTime("year")}-${GJ_nowTime("mon")}`;
      let day = `${GJ_nowTime("year")}-${GJ_nowTime("mon")}-${GJ_nowTime("day")}`;
      status.yearDatas = status.initail?.item.filter((s) => {
        return s.yearDate == year;
      })[0];
      status.monDatas = status.yearDatas.yearDetails.filter((t) => {
        return t.monDate == mon;
      })[0];
      if(status.monDatas){
        status.dayDatas = status.monDatas.monDetails.filter((y) => {
        return y.dayDate == day;
      })[0];
      }else{
        status.dayDatas = [];
      }
      
      status.Expense = Number(status.initail.total).toFixed(2);
      status.yearExpense = Number(status.yearDatas.yearTotal).toFixed(2);
      status.monExpense =status.monDatas? Number(status.monDatas.monTotal).toFixed(2):0;
      status.dayExpense = status.dayDatas? Number(status.dayDatas?.dayTotal).toFixed(2): 0;
      methodFun.getDayData(7);
      methodFun.getMonData(6);
    },
    // 获取天数数据
    getDayData:(num)=> {
      console.log(status.monDatas,num,"day");
      let data = status.monDatas?status.monDatas.monDetails:[];
      let year = GJ_nowTime("year");
      let mon = GJ_nowTime("mon");
      let day = GJ_nowTime("day");
      let beforeMon = new Date(year, mon - 1, 0).getDate();
      if (day >= num) {
        for (let i = 0; i < num; i++) {
          status.xAxisDay.unshift(
            `${year}/${mon}/${day - i > 9 ? day - i : "0" + (day - i)}`
          );
        }
      } else {
        let gap = Math.abs(day - num);
        for (let i1 = 0; i1 < day; i1++) {
          status.xAxisDay.unshift(
            `${year}/${mon}/${day - i1 > 9 ? day - i1 : "0" + (day - i1)}`
          );
        }
        for (let i2 = 0; i2 < gap; i2++) {
          status.xAxisDay.unshift(`${year}/${"0" + (mon - 1)}/${beforeMon - i2}`);
        }
      }
      // console.log("x轴数据",status.xAxisDay);
      status.xAxisDay.forEach((item) => {
        let result = null;
        data.forEach((t) => {
          let st = t.dayDate.replace(/-/g, "/");
          if (st == item) {
            status.yAxisDay.push(Number(t.dayTotal).toFixed(2));
            result = true;
          }
        });
        if (!result) {
          status.yAxisDay.push(0);
        }
      });
      // console.log("y轴数据",status.yAxisDay);
      let dayEct = echarts.init(status.dayEcharts);
      let dayOption = {
        xAxis: {
          type: "category",
          data: (() => {
            let arr = status.xAxisDay.map((item) => {
              let ali = item.split("/");
              return `${ali[1]}/${ali[2]}`;
            });
            return arr;
          })(),
        },
        yAxis: {
          type: "value",
        },

        title: {
          show: true,
          text: "近七天消费一览",
          subtext: `${year}年`,
          left: "center",
        },
        grid: {
          show: true,
        },
        tooltip: {
          show: true,
          trigger: "axis",
        },
        series: [
          {
            name: "今日消费",
            type: "bar",
            smooth: true,
            areaStyle: {},
            data: status.yAxisDay,
            label: {
              show: true,
            },
          },
        ],
      };
      dayEct.setOption(dayOption);
    },
    getMonData:(num)=> {
      let data = status.yearDatas.yearDetails;
      let year = GJ_nowTime("year");
      let mon = GJ_nowTime("mon");
      if (mon >= num) {
        console.log(1);
        for (let i = 0; i < num; i++) {
          status.xAxisMon.unshift(`${year}/${mon - i > 9 ? mon - i : "0" + (mon - i)}`);
        }
        
      } else {
        let gap = Math.abs(mon - num);
        for (let i1 = 0; i1 < mon; i1++) {
          status.xAxisMon.unshift(
            `${year}/${mon - i1 > 9 ? mon - i1 : "0" + (mon - i1)}`
          );
        }
        for (let i2 = 0; i2 < gap; i2++) {
          status.xAxisMon.unshift(`${year - 1}/${12 - i2}`);
        }
      }
      status.xAxisMon.forEach((item) => {
        let result = null;
        data.forEach((t) => {
          let st = t.monDate.replace(/-/g, "/");
          if (st == item) {
            status.yAxisMon.push(Number(t.monTotal).toFixed(2));
            result = true;
          }
        });
        if (!result) {
          status.yAxisMon.push(0);
        }
      });
      
      let dayEct = echarts.init(status.monEcharts);
      let monOption = {
        xAxis: {
          type: "category",
          data: status.xAxisMon,
        },
        yAxis: {
          type: "value",
        },

        title: {
          show: true,
          text: "近半年消费一览",
          subtext: (() => {
            let arr = [];
            status.xAxisMon.forEach((item) => {
              arr.push(item.split("/")[0]);
            });
            let ali = [...new Set(arr)];
            if (ali.length > 1) {
              let min = Math.min(...ali);
              let max = Math.max(...ali);
              return `${min}年-${max}年`;
            } else {
              return `${ali[0]}年`;
            }
          })(),
          left: "center",
        },
        grid: {
          show: true,
        },
        tooltip: {
          show: true,
          trigger: "axis",
        },
        series: [
          {
            name: "本月消费",
            type: "bar",
            smooth: true,
            areaStyle: {},
            data: status.yAxisMon,
            label: {
              show: true,
            },
          },
        ],
      };
      dayEct.setOption(monOption);
    },
    details:(val)=> {
      status.Visible = !status.Visible;
      let xdata = [];
      if (val == 4) {
        let arrs = [];
        let arr = status.dayDatas.dayDetails;
        arr.forEach((item) => {
          arrs.push(item);
        });
        xdata = methodFun.getdetails(arrs);
      } else if (val == 3) {
        let arrs = [];

        let arr = status.monDatas.monDetails;
        arr.forEach((item0) => {
          console.log(item0, "item0");
          item0.dayDetails.forEach((item1) => {
            arrs.push(item1);
          });
        });
        xdata = methodFun.getdetails(arrs);
      } else if (val == 2) {
        let arrs = [];
        let arr = status.yearDatas.yearDetails;
        arr.forEach((item0) => {
          console.log(item0, "item0");
          item0.monDetails.forEach((item1) => {
            item1.dayDetails.forEach((item2) => {
              arrs.push(item2);
            });
          });
        });
        xdata = methodFun.getdetails(arrs);
      } else {
        let arrs = [];
        let arr = status.initail.item;
        arr.forEach((item0) => {
          item0.yearDetails.forEach((item1) => {
            item1.monDetails.forEach((item2) => {
              item2.dayDetails.forEach((item3) => {
                arrs.push(item3);
              });
            });
          });
        });
        xdata = methodFun.getdetails(arrs);
      }

      let detailEch = echarts.init(status.detailEcharts);
      let option = {
        tooltip: {
          trigger: "item",
        },
        legend: {
          top: "5%",
          left: "center",
        },
        series: [
          {
            name: "消费金额",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "40",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: xdata,
          },
        ],
      };
      detailEch.setOption(option);
    },
    getdetails:(datas)=> {
      let xdata = [];
      datas.forEach((item) => {
        // let name = item.desc || item.type;
        let name = item.type;
        let result = xdata.some((item1) => {
          return item1.name == name;
        });
        if (!result) {
          xdata.push({ name: name });
        }
      });
      xdata = [...new Set(xdata)];
      xdata.forEach((item1, index1) => {
        let arr = datas.filter((item2) => {
          //   let type = item2.desc || item2.type;
          let type = item2.type;
          return type == item1.name;
        });
        let num = arr.reduce((before, now) => {
          return before + now.money;
        }, 0);
        xdata[index1].value = num;
      });
      return xdata;
    }
  }
  return {
    status,
    methodFun
  }
}

export default expenseListJS;